package com.pb.b2b.common.exception2;

import java.util.Iterator;
import java.util.Map;

import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pb.b2b.util.FacesUtils;

public class CustomExceptionHandler extends ExceptionHandlerWrapper {
	private static final Logger log = LoggerFactory.getLogger(CustomExceptionHandler.class.getCanonicalName());
	private ExceptionHandler wrapped;

	CustomExceptionHandler(ExceptionHandler exception) {
		this.wrapped = exception;
	}

	@Override
	public ExceptionHandler getWrapped() {
		return wrapped;
	}

	@Override
	public void handle() throws FacesException {

		final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
		while (i.hasNext()) {
			ExceptionQueuedEvent event = i.next();
			ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

			// get the exception from context
			Throwable t = context.getException();

			// final FacesContext fc = FacesContext.getCurrentInstance();
			final Map<String, Object> requestMap = FacesUtils.getFacesContext().getCurrentInstance().getExternalContext().getRequestMap();
			// final NavigationHandler nav = fc.getApplication()
			// .getNavigationHandler();

			// here you do what ever you want with exception
			try {

				// log error ?
				log.error("ERROR", "Critical Exception!", t);

				// redirect error page
				requestMap.put("exceptionMessage", t.getMessage());
				// nav.handleNavigation(fc, null, "/error");
				// fc.renderResponse();
				FacesUtils.addMessage(FacesMessage.SEVERITY_ERROR, "ERROR_SYSTEM");

				// remove the comment below if you want to report the error in a
				// jsf error message
				// JsfUtil.addErrorMessage(t.getMessage());

			} finally {
				// remove it from queue
				i.remove();
			}
		}
		// parent hanle
		getWrapped().handle();
	}
}